package org.jverify.utility.smtp;

/**
 * @author Yiannis Mavroukakis
 */
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.mail.smtp.SMTPMessage;
import com.sun.mail.smtp.SMTPTransport;

public final class MailSender {

	private static final Logger LOG = LoggerFactory.getLogger(MailSender.class);

	private MailSender() {
	};

	private static final String MAIL_HOST = "mail.host"; //$NON-NLS-1$

	public static boolean sendMail(final String to, final String cc, final String from, final String smtpHost,
			final String subject, final String body) throws MessagingException {

		final Properties props = new Properties();
		props.put(MAIL_HOST, smtpHost);
		final Session session = Session.getInstance(props);
		session.setDebug(false);

		final URLName urlName = new URLName(smtpHost);
		final SMTPTransport transport = new SMTPTransport(session, urlName);
		transport.connect();

		try {
			final MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] address = InternetAddress.parse(to, false);
			msg.setRecipients(Message.RecipientType.TO, address);
			if (cc != null) {
				address = InternetAddress.parse(cc, false);
				msg.setRecipients(Message.RecipientType.CC, address);
			}

			msg.setSubject(subject);
			msg.setSentDate(new Date());

			msg.setText(body);

			final SMTPMessage message = new SMTPMessage(msg);

			Transport.send(message);
		}
		catch (final MessagingException me) {
			LOG.error("{}", me.getLocalizedMessage());
			return false;
		}
		return true;
	}
}
